package com.mdp.im.core.service.admin;

import com.mdp.core.api.CacheHKVService;
import com.mdp.im.core.utils.msg.MsgAction;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qqkj
 *
 */
@Service
public class GroupAdminService {

	public static  String prefix="im_group_admin_";

 	public static CacheHKVService redisTemplate;


	@Autowired
	public  void setRedisTemplate(CacheHKVService redisTemplate) {
		GroupAdminService.redisTemplate = redisTemplate;
	}
	
	 public static void setGroupMsgAction(String groupId,String msgAction,Long millSec){
		if(millSec==null) {
			millSec=new Long(3600000);
		}
		Map<String,Object> group=getGroupActions(groupId);
		Date d=new Date();
		if(group==null) {
			group=new HashMap<>(); 
			group.put(msgAction, Long.valueOf(d.getTime()+"")+millSec);
			putGroupActions(groupId,group);
		}else {
			group.put(msgAction, Long.valueOf(d.getTime()+"")+millSec);
			putGroupActions(groupId,group);
		}
		
	}
	
	 public static void forbiddenGroupWords(String groupId,Long millSec) {
		setGroupMsgAction(groupId, MsgAction.group_forbiddenGroupWords,millSec);
	}
	 public static void forbiddenJoin(String groupId,Long millSec) {
		setGroupMsgAction(groupId, MsgAction.group_forbiddenJoin,millSec);
	}
	 public static void allowGroupWords(String groupId) {
		Map<String,Object> group=getGroupActions(groupId);
		if(group!=null) {
			group.remove(MsgAction.group_forbiddenGroupWords);
			putGroupActions(groupId,group);
		}
	} 
	

	 public static boolean isForbiddenGroupWords(String groupId) {
		return isMsgAction(groupId, MsgAction.group_forbiddenGroupWords);
	} 

	 public static boolean isForbiddenJoin(String groupId) {
		return isMsgAction(groupId, MsgAction.group_forbiddenJoin);
	} 
	 public static boolean isMsgAction(String groupId,String msgAction) {
		Map<String,Object> group=getGroupActions(groupId);
		if(group!=null) {
			Long i=(Long) group.get(msgAction);
			if(i==null) {
				return false;
			}else {
				Date d=new Date();
				return i.longValue()>d.getTime();
			}
			
			
		}else {
			return false;
		}
	} 

	 public static void allowJoin(String groupId) {
		Map<String,Object> group=getGroupActions(groupId);
		if(group!=null) {
			group.remove(MsgAction.group_forbiddenJoin);
			putGroupActions(groupId,group);
		}
	}


	public static  Map<String,Object> getGroupActions(String groupId){
		return (Map<String, Object>) redisTemplate.get(prefix+groupId,groupId);
	}

	public static  void putGroupAction(String groupId,String action,Long millSec){
		Map<String, Object> ga=getGroupActions(groupId);
		ga.put(action,millSec);
		putGroupActions(groupId,ga);
	}

	public static  void putGroupActions(String groupId,Map<String,Object> actions){
		redisTemplate.put(prefix+groupId,groupId,actions);
	}
}
